package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.pojo.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.List;

/**
 * @author Alfred
 * @description TODO
 * @date 2021/4/26 11:17
 */
@Service
public class SpitService {
    @Autowired
    private SpitDao spitDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * fetch data by rule id
     *
     * @description  查询全部记录
     * @param
     * @return
     */
    public List<Spit> findAll(){
        return spitDao.findAll();
    }

    /**
     * fetch data by rule id
     *
     * @description  根据主键查询实体
     * @param
     * @return
     */
    public Spit findById(String id){
        Spit spit = spitDao.findById(id).get();
        return spit;
    }

    /**
     * fetch data by rule id
     *
     * @description  增加吐槽
     * @param
     * @return
     */
    public void add(Spit spit){
        spit.set_id(idWorker.nextId()+"");//主键值
        spitDao.save(spit);
    }

    /**
     * fetch data by rule id
     *
     * @description  修改
     * @param
     * @return
     */
    public void update(Spit spit){
        spitDao.save(spit);
    }

    /**
     * fetch data by rule id
     *
     * @description  删除
     * @param
     * @return
     */
    public void deleteById(String id){
        spitDao.deleteById(id);
    }

    /**
     * fetch data by rule id
     *
     * @description  根据上级Id查询吐槽列表
     * @param
     * @return
     */
    public Page<Spit> findByParentid(String parentid,int page,int size){
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return spitDao.findByParentid(parentid,pageRequest);
    }

    /**
     * fetch data by rule id
     *
     * @description  点赞     这种设置简单但并不高效，我们只需要将点赞数+1即可   没必要查出所有字段再保存所有字段
     * 可以使用MongoTemplate类来对某列实现操作
     * @param
     * @return
     */
    /*public void updateThumbup(String id){
        Spit spit = spitDao.findById(id).get();
        spit.setThumbup(spit.getThumbup()+1);
        spitDao.save(spit);//点赞并保存
    }*/
    public void updateThumbup(String id){
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.inc("thumbup",1);
        mongoTemplate.updateFirst(query,update,"spit");
    }

}
